#! /usr/bin/env python
#coding=utf-8
from .. import config
import hashlib, datetime, random

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in config.ALLOWED_EXTENSIONS

def allowed_size(size):
    return True if size<=config.MAX_CONTENT_LENGTH else False

def slugify(text, delim=u'-'):
    """Generates an ASCII-only slug."""
    result = []
    slug_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
    for word in slug_re.split(text.lower()):
        if word:
            result.append(word)
    return unicode(delim.join(result))

def valid_datetime(datetime):
    """
    >>> valid_datetime('2010-02-28')
    True
    >>> valid_datetime('2010-02-29')
    False    
    """
    r = re.compile(r"^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))?$")
    p = r.match(datetime)
    valid = True if p else False
    return valid

def mark_md5(key):
    md5 = hashlib.md5()
    md5.update(key)
    return md5.hexdigest()

def upload_file(f, filename, rename=True):
    if not allowed_size(len(f)):
        return {'err':u'文件超出可上传大小','msg':''}
    now = datetime.datetime.now()
    path = os.path.join(config.UPLOAD_FOLDER, now.strftime('%Y-%m'))
    if not os.path.isdir(path):
        os.makedirs(path)
    if rename:        
        filename = now.strftime('%Y%m%d%H%M%%S%f') + ''.join(random.sample('ABCDEF',2)) + os.path.splitext(filename)[-1]
    try:
        fout = open(os.path.join(path, filename),'wb')
        fout.write(f)
        fout.close()
        f_url = '%s/%s' % (config.UPLOAD_ROOT,filename)
    except:
        return {'err':u'保存文件失败','msg':''}
    return {'err':'','msg':f_url}
    